package com.liuwa.framework.aspectj;

import com.liuwa.common.exception.ParameterException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @ClassName: ValidationAspect
 * @Author: Liuwa
 * @Description: 请求参数校验切面
 * @Date: 2022/5/10 19:45
 * @Version: 1.0
 */
@Order(1)
@Aspect
@Component
public class ValidationAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());


    //切点
    @Pointcut("@annotation(com.liuwa.common.annotation.Validation)")
    public  void validationHandler() {}

    @Before("validationHandler()")
    public void before(JoinPoint point) throws Throwable{
        Object[] args = point.getArgs();
        for(Object obj : args){
            Class clazz = obj.getClass();
            if(!clazz.isAnnotationPresent(ApiModel.class)){
                continue;
            }
            for(Field field : clazz.getDeclaredFields()){
                if(field.isAnnotationPresent(ApiModelProperty.class)){
                    ApiModelProperty property = field.getAnnotation(ApiModelProperty.class);
                    if(property.required() && !property.hidden()){
                        String label = property.value();
                        field.setAccessible(true);
                        Object value = field.get(obj);
                        if(value == null || (value instanceof String && "".equals(((String) value).trim()))){
                            throw new ParameterException("参数[" + label + "]不能为空");
                        }
                    }
                }
            }
        }

    }

}